package power.game.sixtysix.entity;

import java.util.Arrays;
import java.util.Collections;


public class Stack {

	private static final int MAX_CARDS = 20;
	
	private int cardsInStack;
	private Integer[] cardIdArray;
	private Card[] cardArray;
	
	public Stack() {
		cardsInStack = MAX_CARDS;
		cardIdArray = new Integer[MAX_CARDS];
		cardArray = new Card[MAX_CARDS];
		for (int i = 0; i < MAX_CARDS; i++) {
			cardIdArray[i] = i;
			cardArray[i] = new Card(i);
		}
		shuffle();
	}
	
	public Integer popCard() {
		if (cardsInStack > 0) {
			cardsInStack--;
			return cardIdArray[cardsInStack];
		} else {
			return -1;
		}
	}
	
	public boolean isEmpty() {
		return cardsInStack == 0;
	}
	
	public Integer getTalon() {
		return cardIdArray[0];
	}
	
	public Card getTalonCard() {
		return cardArray[cardIdArray[0]];
	}
	
	public Integer switchTalon(Integer newTalon) {
		Integer tmp = -1;
		if (verfyTalon(newTalon)) {
			tmp = cardIdArray[0];
			cardIdArray[0] = newTalon;
		}
		return tmp;
	}
	
	public String toString() {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < cardsInStack; i++) {
			sb.append(cardArray[cardIdArray[i]]);
			sb.append(";");
		}
		return sb.toString();
	}
	
	private void shuffle() {
		Collections.shuffle(Arrays.asList(cardIdArray));
	}
	
	private boolean verfyTalon(Integer newTalon) {
		boolean result = false;
		result = cardsInStack > 0;
		return result;
	}
}
